Generally, people want one of two things from malloc().
Allocating a single object on the heap: this is important for data structures where you have a tree or list node and want to link pointers together.
Code:
node *p= malloc(sizeof *p);
if (p != NULL) {
p->data = getValue();
// fill the rest of the node
}
Simulating an array with pointer: other times you might need an array structure where the size is determined at run time, the size is flexible, or both.
Code:
object *arr;
int size;
printf("Enter the size of the array: ");
size = getValue();
arr = malloc(size * sizeof arr[0]);
if (arr == NULL) {
fprintf(stderr, "array could not be allocated\n");
return 1;
}
// use arr
The multiplication step here is all you need to really do to ask for enough bytes for the array.
I haven't talked about sizeof yet, but all that the operator does is give the size of its operand in bytes. The argument can be any data type. If you say sizeof(int), it gives you the size of an int.
Feel free to use sizeof like that your whole life. It's not wrong, but some people find it error prone. After all, if the type of a variable changes at some stage of the development life-cycle, now you have to change the variable in at least two places. There is an easier way to use sizeof, which is also the way I showed. If you can dereference your pointer, and make that your operand to sizeof, it will never be wrong, even if the type changes. So, again, if the type changes at some stage, you have to change the variable in less places.
Additionally:
The if statements matter: when malloc() fails, it will return a NULL pointer. Check for that and respond accordingly, always. You cannot use NULL pointers.
Free your memory when your done.
Code:
free(p);
p = NULL;
free(arr);
arr = NULL;
Now with this you understand the two most important reasons why people call malloc() and how to successfully call it in those cases. Once you have this under your belt, read about dynamic 2D arrays, and then you'll be as equipped as anyone. At the same time, please don't consider this post exhaustive, and consult other references you may have found again. As a warning, knowing how and why to call malloc() does not mean that you've programmed correctly. Memory leaks can still happen and it's the programmer's job to look for any of them, either with experience (spotting problems by looking at code) or tools (like valgrind), or ideally a combination of the two, and fix them.
malloc(3): allocate/free dynamic memory - Linux man page